/**
 * 工时统计相关工具函数
 */

import * as XLSX from 'xlsx';
import { ProjectWorkloadSummary, ExportStatsOptions } from '@/types/workloadStats';
import { WorkloadRecord } from '@/types/workload';

/**
 * 导出工时统计数据到 Excel
 */
export function exportWorkloadStatsToExcel(
  summaries: ProjectWorkloadSummary[],
  details: WorkloadRecord[],
  options: ExportStatsOptions
) {
  const workbook = XLSX.utils.book_new();

  // 项目汇总工作表
  const summaryData = summaries.map(project => ({
    '项目名称': project.projectName,
    '项目标识': project.projectIdentifier,
    '总工时(小时)': project.totalHours,
    '参与成员数': project.memberCount,
    '工作天数': project.workDays,
    '平均日工时': project.avgDailyHours.toFixed(2),
    '开始日期': formatDate(project.startDate),
    '结束日期': formatDate(project.endDate),
    '工时类型': project.workloadTypes.join(', ')
  }));

  const summarySheet = XLSX.utils.json_to_sheet(summaryData);
  XLSX.utils.book_append_sheet(workbook, summarySheet, '项目汇总');

  // 成员统计工作表
  const memberData: any[] = [];
  summaries.forEach(project => {
    project.memberStats.forEach(member => {
      memberData.push({
        '项目名称': project.projectName,
        '成员姓名': member.memberName,
        '工时(小时)': member.totalHours,
        '工作天数': member.workDays,
        '平均日工时': member.avgDailyHours.toFixed(2),
        '项目占比(%)': member.percentage.toFixed(2)
      });
    });
  });

  const memberSheet = XLSX.utils.json_to_sheet(memberData);
  XLSX.utils.book_append_sheet(workbook, memberSheet, '成员统计');

  // 详细记录工作表（如果包含详情）
  if (options.includeDetails && details.length > 0) {
    const detailData = details.map(record => ({
      '日期': formatDate(record.date),
      '项目名称': record.pilotName,
      '成员姓名': record.memberName,
      '工时类型': record.workloadTypeName,
      '工时(小时)': record.hours,
      '描述': record.description || ''
    }));

    const detailSheet = XLSX.utils.json_to_sheet(detailData);
    XLSX.utils.book_append_sheet(workbook, detailSheet, '详细记录');
  }

  // 生成文件名
  const fileName = `工时统计报表_${formatDate(options.dateRange.startDate)}_${formatDate(options.dateRange.endDate)}.xlsx`;

  // 导出文件
  XLSX.writeFile(workbook, fileName);
}

/**
 * 导出工时统计数据到 CSV
 */
export function exportWorkloadStatsToCSV(
  summaries: ProjectWorkloadSummary[],
  options: ExportStatsOptions
) {
  const csvData = summaries.map(project => ({
    '项目名称': project.projectName,
    '项目标识': project.projectIdentifier,
    '总工时(小时)': project.totalHours,
    '参与成员数': project.memberCount,
    '工作天数': project.workDays,
    '平均日工时': project.avgDailyHours.toFixed(2),
    '开始日期': formatDate(project.startDate),
    '结束日期': formatDate(project.endDate),
    '工时类型': project.workloadTypes.join(', ')
  }));

  const worksheet = XLSX.utils.json_to_sheet(csvData);
  const csv = XLSX.utils.sheet_to_csv(worksheet);

  // 添加 BOM 以支持中文
  const BOM = '\uFEFF';
  const blob = new Blob([BOM + csv], { type: 'text/csv;charset=utf-8;' });

  // 生成文件名
  const fileName = `工时统计报表_${formatDate(options.dateRange.startDate)}_${formatDate(options.dateRange.endDate)}.csv`;

  // 下载文件
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', fileName);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/**
 * 导出工时统计数据到 JSON
 */
export function exportWorkloadStatsToJSON(
  summaries: ProjectWorkloadSummary[],
  details: WorkloadRecord[],
  options: ExportStatsOptions
) {
  const exportData = {
    exportInfo: {
      exportTime: new Date().toISOString(),
      dateRange: options.dateRange,
      projectCount: summaries.length,
      totalRecords: details.length
    },
    projectSummaries: summaries,
    ...(options.includeDetails && { detailRecords: details })
  };

  const jsonString = JSON.stringify(exportData, null, 2);
  const blob = new Blob([jsonString], { type: 'application/json;charset=utf-8;' });

  // 生成文件名
  const fileName = `工时统计数据_${formatDate(options.dateRange.startDate)}_${formatDate(options.dateRange.endDate)}.json`;

  // 下载文件
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', fileName);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
}

/**
 * 计算工时统计摘要
 */
export function calculateWorkloadSummary(summaries: ProjectWorkloadSummary[]) {
  const totalProjects = summaries.length;
  const totalHours = summaries.reduce((sum, project) => sum + project.totalHours, 0);
  const totalMembers = new Set(
    summaries.flatMap(project => 
      project.memberStats.map(member => member.memberId)
    )
  ).size;
  const avgHoursPerProject = totalProjects > 0 ? totalHours / totalProjects : 0;
  const avgMembersPerProject = totalProjects > 0 ? 
    summaries.reduce((sum, project) => sum + project.memberCount, 0) / totalProjects : 0;

  return {
    totalProjects,
    totalHours,
    totalMembers,
    avgHoursPerProject,
    avgMembersPerProject
  };
}

/**
 * 生成颜色调色板
 */
export function generateColorPalette(count: number): string[] {
  const colors = [
    '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
    '#13c2c2', '#eb2f96', '#fa8c16', '#a0d911', '#2f54eb',
    '#fa541c', '#eb2f96', '#52c41a', '#fadb14', '#1890ff'
  ];

  if (count <= colors.length) {
    return colors.slice(0, count);
  }

  // 如果需要更多颜色，生成渐变色
  const result = [...colors];
  const baseColors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'];
  
  for (let i = colors.length; i < count; i++) {
    const baseColor = baseColors[i % baseColors.length];
    const opacity = 0.3 + (0.7 * ((i - colors.length) % 3)) / 3;
    result.push(adjustColorOpacity(baseColor, opacity));
  }

  return result;
}

/**
 * 调整颜色透明度
 */
function adjustColorOpacity(color: string, opacity: number): string {
  // 简单的颜色透明度调整
  const hex = color.replace('#', '');
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  
  return `rgba(${r}, ${g}, ${b}, ${opacity})`;
}